//
//  SCNRequestManager.swift
//  ShoucainuSwift
//
//  Created by 王家旭 on 2017/3/9.
//  Copyright © 2017年 Riluee. All rights reserved.
//

import UIKit
import Alamofire
import ObjectMapper

class SCNRequestManager: NSObject {
    
    static let manager = SCNRequestManager()
    

    /// GET
    static func getRequest(_ URL:String,completeBlock:@escaping ((_ response:DataResponse<Any>)->Void)){
        
        Alamofire.request(URL).responseJSON { response in
            
            if response.result.error == nil {
                // 成功
                let text:String = NSString(data: response.data!, encoding: String.Encoding.utf8.rawValue)! as String
                
                printLog(text)
                
            }else{
                
                printLog(response.result.error)
                
            }
            
            completeBlock(response)
        }
        
    }
    
    
    /// POST
    static func postRequest(_ param: [String : String],URL: String,completeBlock:@escaping ((_ response:DataResponse<Any>) -> Void)) {

        
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        
        var parameters = SCNCommonParamter().commonParam
        /// 拼接公共参数
        for (k, v) in param {
            parameters[k] = v
        }
   
        
        
        Alamofire.request(URL, method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in
            
//            saveCookie(response)
            
            if response.result.isFailure {
                // 请求失败
                NotificationCenter.default.post(name: Notification.Name.State.RequestFailure, object: nil)
            }else {
                
                //printLog("\(URL)\n\(String(describing: response.result.value))")
                
                let value = response.result.value as! Dictionary<String, Any>
                
                let state = value["status"] as! Int
                
                if state != 1 {
                    // 请求错误
                    NotificationCenter.default.post(name: Notification.Name.State.RequestError, object: nil, userInfo: ["errmsg" : value["errmsg"] ?? "请求错误"])
                }else {

                    // 请求成功

                    NotificationCenter.default.post(name: Notification.Name.State.RequestSuccess, object: nil)
                    
                    completeBlock(response)
                }
                
            }
            
            
            UIApplication.shared.isNetworkActivityIndicatorVisible = false
        }
        
        

    }

    //重启有时候会导致cookie丢失，使得数据不匹配
    static func saveCookie(_ response: DataResponse<Any>) {
        
        let headerFields = response.response?.allHeaderFields as! [String: String]
        let url = response.request?.url
        let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url!)
        var cookieArray = [ [HTTPCookiePropertyKey : Any ] ]()
        for cookie in cookies {
            cookieArray.append(cookie.properties!)
        }
        //手动保存cookie
        UserDefaults.standard.set(cookieArray, forKey: "alamofire_cookies")
    }
}

struct SCNCommonParamter {
    
    /// 添加公共参数
    
    static let version = Bundle.main.infoDictionary! ["CFBundleShortVersionString"] as! String
    static let app_name = "shoucainu"
    static let client = "IOS"
    static let deviceid = UIDevice.current.identifierForVendor!.uuidString
    static let idfa = UIDevice.current.identifierForVendor!.uuidString
    static let sign = "IOS|cyApp@1616".md5()
    
    public let commonParam = [
        "version" : version,
        "app_name" : app_name,
        "_client_" : client,
        "_deviceid_" : deviceid,
        "idfa" : idfa,
        "_sign_" : sign
    ]
}


